from rest_framework import serializers
from order import models
from django.conf import settings
from rest_framework.serializers import ValidationError
from home.models import Project

from uuid import uuid4


class ProjectOrderCreateModelSerializer(serializers.ModelSerializer):
    """
    创建商品订单
    """
    num = serializers.CharField(write_only=True)
    good_id = serializers.CharField(write_only=True)
    price = serializers.CharField(write_only=True)

    class Meta:
        model = models.Order
        fields = ['num', 'good_id', 'price']

    def create(self, validated_data):
        """
        创建
        """
        """
        {
        'num': 1, 
        'good_id': '4', 
        'price': '998',
          }
        """
        # 3 处修改  获取token

        # comment_request_dic = self.context['request'].data
        # 登录用户
        user = self.context['request'].user
        good_id = validated_data.get('good_id', None)
        price = validated_data.get('price', None)
        num = validated_data.get('num', None)
        project_obj = Project.objects.get(pk=good_id)
        total_price = float(price) * int(num)
        order_obj = models.Order.objects.create(subject=project_obj.title, total_amount=total_price,
                                                out_trade_no=str(uuid4()), user_id=user.id, project_id=project_obj.id)
        self.context['order_id'] = order_obj.id
        return order_obj


class ProjectOrderUpdateModelSerializer(serializers.ModelSerializer):
    """
    修改商品订单
    """
    order_id = serializers.CharField(write_only=True)

    class Meta:
        model = models.Order
        fields = ['order_id']

    def update(self, instance, validated_data):
        """
        修改
        """
        # print(instance, '>>>>>')
        # print(validated_data, '>>>>')
        models.Order.objects.filter(pk=validated_data.get('order_id')).update(order_status=1)

        return instance


# class ProjectOrderAllModelSerializer(serializers.ModelSerializer):
#     """
#     ymq
#     订单
#     """
#
#     class Meta:
#         model = models.Order
#         fields = ['id']
